#include "config.h"

#include <fstream>
#include <iostream>

#ifdef _WIN32
static char configpath[] = "";
#elif __linux__
#include <sys/stat.h>
#include <unistd.h>
#include <cstdio>
static char configpath[] = "/.Timer/config.txt";
#endif

void Timer::save_chronograph_time(unsigned int h, unsigned int m, unsigned int s)
{
	const char *home = getenv("HOME");
	std::string filepath = home;
	filepath.append(configpath);
	std::fstream file(filepath, std::ios_base::out); // 打开文件
	if(file.is_open() == false){
		std::cerr << "打开文件失败\n";
		make_ConfigFile();
	}
	// std::cerr << "h = " << h << std::endl;
	// std::cerr << "m = " << m << std::endl;
	// std::cerr << "s = " << s << std::endl;
	file << h << std::endl;
	file << m << std::endl;
	file << s << std::endl;
	file.close(); // 关闭文件
}

void Timer::get_chronograph_time(unsigned int &h, unsigned int &m, unsigned int &s)
{
	const char *home = getenv("HOME");
	std::string filepath(home);
	filepath.append(configpath);
	std::fstream file(filepath, std::ios::in); // 打开文件
	if(file.is_open() == false){ // 文件打开失败
		h = m = s = 0; // 返回0
	}
	file >> h;
	file >> m;
	file >> s;
	// std::cerr << "h = " << h << std::endl;
	// std::cerr << "m = " << m << std::endl;
	// std::cerr << "s = " << s << std::endl;
	file.close();
	Timer::save_chronograph_time(0,0,0);
}

int Timer::make_ConfigFile()
{
#ifdef __linux__
	// Linux配置文件目录 ~/.Timer/config.txt
	const char *home = getenv("HOME"); // 获取 ~ 目录位置
	// std::cout << "HOME = "<< home << std::endl;
	if (home == nullptr) {
		return -1;
	}
	// 判断 .Timer/目录是否存在
	std::string dirpath(home);
	dirpath.append("/.Timer");
	struct stat status;
	if(stat(dirpath.c_str(), &status) == -1){ // ENOENT 文件不存在
		if(errno == ENOENT){ // 目录不存在
			std::cerr << "目录" << dirpath << "不存在" << std::endl;
			// 创建目录
			if(mkdir(dirpath.c_str(), 0755) != 0){ // 创建目录 权限：rwxrwxr-x
				std::cerr << "创建目录：" << dirpath << "失败" << std::endl;
				return -1;
			}
		}
		return 0;
	}
	// 判断文件 config.txt是否存在
	std::string filepath = dirpath + "/config.txt";
	if(access(filepath.c_str(), F_OK) == 0){ // 文件存在
		return 0;
	}else{ // 文件不存在
		std::fstream file(filepath, std::ios::out); // 创建文件
		file.close();
		return 0;
	}
#endif
}
